package com.huilian.iotbox.admin.wap.service.impl;

import com.huilian.iotbox.admin.wap.dao.RoleDao;
import com.huilian.iotbox.admin.wap.dao.RolePermissionTempDao;
import com.huilian.iotbox.admin.wap.service.PermissionService;
import com.huilian.iotbox.admin.wap.service.RolePermissionTempService;
import com.huilian.iotbox.admin.wap.service.UserRoleService;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.dto.RoleDto;
import com.huilian.iotbox.data.dto.RolePermissionTempDto;
import com.huilian.iotbox.data.enums.PermissionOpenSettingEnum;
import com.huilian.iotbox.data.enums.PermissionStatusEnum;
import com.huilian.iotbox.data.enums.RoleTypeEnum;
import com.huilian.iotbox.data.enums.UserStatusEnum;
import com.huilian.iotbox.data.po.Permission;
import com.huilian.iotbox.data.po.RolePermissionTemp;
import com.huilian.iotbox.data.vo.RolePermissionTempVo;
import com.huilian.iotbox.data.vo.RoleVo;
import com.huilian.iotbox.data.vo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LinYinDong
 * @date 2024/10/10 下午6:03
 */
@Service
public class RolePermissionTempServiceImpl implements RolePermissionTempService {

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RolePermissionTempDao rolePermissionTempDao;

    /**
     * 添加/修改角色权限模板
     *
     * @param rolePermissionTempDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse editRolePermissionTemp(RolePermissionTempDto rolePermissionTempDto) {
        if (StringUtils.isEmpty(rolePermissionTempDto.getName())) {
            return ServerResponse.createByErrorMessage("角色名称不能为空");
        }
        if (StringUtils.isEmpty(rolePermissionTempDto.getPermissionIdList()) || rolePermissionTempDto.getPermissionIdList().size() == 0) {
            rolePermissionTempDto.setPermissionIdList(new ArrayList<>());
        }

        List<Permission> permissionList = new ArrayList<>();
        if (rolePermissionTempDto.getPermissionIdList().size() > 0) {
            Permission permissionCondition = new Permission();
            permissionCondition.setStatus(PermissionStatusEnum.OPEN.getCode());
            permissionCondition.setOpenSetting(PermissionOpenSettingEnum.OPEN.getCode());
            permissionCondition.setUserInfo(rolePermissionTempDto.getUserInfo());
            permissionList = permissionService.findAllPermissionByIdListAndOther(rolePermissionTempDto.getPermissionIdList(), permissionCondition);
        }

        Map<Integer, Permission> permissionTempMap = new HashMap<>();
        if (!StringUtils.isEmpty(permissionList) && permissionList.size() > 0) {
            permissionTempMap = permissionList.stream().collect(Collectors.toMap(Permission::getId, a -> a, (k1, k2) -> k1));
        }

        //添加
        RoleDto roleDto = new RoleDto();
        if (StringUtils.isEmpty(rolePermissionTempDto.getRoleId())) {
            roleDto.setName(rolePermissionTempDto.getName());
            roleDto.setType(RoleTypeEnum.MERCHANT.getCode());
            roleDto.setUserId(rolePermissionTempDto.getUserId());
            final Integer result = roleDao.insertAndUserId(roleDto);
            if (result <= 0) {
                throw new RuntimeException("添加角色失败");
            }

            List<RolePermissionTemp> rolePermissionTempList = new ArrayList<>();
            for (Permission permission : permissionList) {
                RolePermissionTemp rolePermissionTemp = new RolePermissionTemp();
                rolePermissionTemp.setRoleId(roleDto.getId());
                rolePermissionTemp.setUserId(rolePermissionTempDto.getUserId());
                rolePermissionTemp.setPermissionId(permission.getId());
                rolePermissionTempList.add(rolePermissionTemp);
            }

            if (rolePermissionTempList.size() > 0) {
                rolePermissionTempDao.batchInsert(rolePermissionTempList);
            }
        } else {
            //修改
            roleDto.setId(rolePermissionTempDto.getRoleId());
            roleDto.setName(rolePermissionTempDto.getName());
            final Integer update = roleDao.updateByName(roleDto);
            if (update <= 0) {
                throw new RuntimeException("修改角色失败");
            }

            //查询原有分配了角色权限功能
            List<RolePermissionTempVo> rolePermissionTempByUserIdList = rolePermissionTempDao.getRolePermissionTempByRoleIdAndPlatformType(rolePermissionTempDto.getRoleId());
            Map<Integer, RolePermissionTempVo> existRolePermissionTempMap = new HashMap<>();
            if (!StringUtils.isEmpty(rolePermissionTempByUserIdList) && rolePermissionTempByUserIdList.size() > 0) {
                existRolePermissionTempMap = rolePermissionTempByUserIdList.stream().collect(Collectors.toMap(RolePermissionTempVo::getPermissionId, a -> a, (k1, k2) -> k1));
            }
            // 列表准备
            RolePermissionTempDto rolePermissionTempDto1 = new RolePermissionTempDto();
            rolePermissionTempDto1.setRoleId(roleDto.getId());
            rolePermissionTempDto1.setUserId(rolePermissionTempDto.getUserId());

            // 添加新权限
            for (Permission permission : permissionList) {
                final RolePermissionTempVo rolePermissionTempVo = existRolePermissionTempMap.get(permission.getId());
                if (!StringUtils.isEmpty(rolePermissionTempVo)) {
                    continue;
                }
                rolePermissionTempDto1.setPermissionId(permission.getId());
                rolePermissionTempDao.insert(rolePermissionTempDto1);
            }

            // 删除旧权限
            for (RolePermissionTempVo rolePermissionTempVo : rolePermissionTempByUserIdList) {
                final Permission permission = permissionTempMap.get(rolePermissionTempVo.getPermissionId());
                if (!StringUtils.isEmpty(permission)) {
                    continue;
                }
                rolePermissionTempDao.deleteByUserIdAndPermissionId(rolePermissionTempVo.getPermissionId(), rolePermissionTempDto.getUserId(), roleDto.getId());
            }
        }

        return ServerResponse.createBySuccess();
    }

    /**
     * 删除角色权限模板
     *
     * @param rolePermissionTempDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse delRole(RolePermissionTempDto rolePermissionTempDto) {
        if (StringUtils.isEmpty(rolePermissionTempDto.getId())) {
            return ServerResponse.createByErrorMessage("缺少id");
        }

        RolePermissionTempDto rPTDto = new RolePermissionTempDto();
        rPTDto.setUserInfo(rolePermissionTempDto.getUserInfo());
        rPTDto.setRoleId(rolePermissionTempDto.getId());
        final RoleVo roleVo = roleDao.getOneRoleByIdAndUserId(rPTDto);
        if (StringUtils.isEmpty(roleVo)) {
            return ServerResponse.createByErrorMessage("不存在该角色");
        }

        if (!RoleTypeEnum.MERCHANT.getCode().equals(roleVo.getType())) {
            return ServerResponse.createByErrorMessage("该角色禁止删除");
        }

        final int count = userRoleService.findSumNormalByRoleId(rolePermissionTempDto.getId(), UserStatusEnum.WRITE_OFF.getCode());
        if (count > 0){
            return ServerResponse.createByErrorMessage("该角色目前有" + count + "个账号关联，暂不能删除");
        }

        final Integer delete = roleDao.delete(roleVo.getId());
        if (delete <= 0) {
            throw new RuntimeException("删除角色失败");
        }
        List<RolePermissionTempVo> list = rolePermissionTempDao.getRolePermissionTempByRoleId(roleVo.getId(), rolePermissionTempDto.getUserInfo());
        if (!ObjectUtils.isEmpty(list)) {
            final Integer del = rolePermissionTempDao.delete(roleVo.getId());
            if (del <= 0) {
                throw new RuntimeException("删除权限模板失败");
            }
        }
        return ServerResponse.createBySuccess();
    }

    @Override
    public List<RolePermissionTempVo> findRolePermissionTempByRoleIdList(Integer roleId, UserInfo userInfo) {
        if (StringUtils.isEmpty(roleId)) {
            throw new RuntimeException("缺少角色Id");
        }
        return rolePermissionTempDao.getRolePermissionTempByRoleId(roleId, userInfo);
    }

}
